<template>
  <section class="wh-full">
    <header class="flex-b plr-16px h-64px bg-#fff rd-4px">
      <a-form ref="searchRormRef" :model="searchFormState" name="searchForm" layout="inline" autocomplete="off" @finish="onFinishSearch">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="searchFormState.name"> </a-input>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button :disabled="disabledSeachBtn" type="primary" html-type="submit">搜索</a-button>
            <a-button key="reset" @click="resetSearchForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </header>
    <section class="main-box bg-#fff rd-4px plr-16px">
      <div class="h-52px flex-b">
        <div class="text-18px font-bold">文件列表</div>
        <div></div>
      </div>
      <div class="main-content" ref="mainContentRef">
        <a-table
          :columns="columns"
          :row-key="(record) => record.id"
          :loading="tableLoading"
          :data-source="tableData"
          :pagination="pageSet"
          :scroll="{ x: 1500, y: tableHeight }"
          :locale="{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }"
          @change="handleTableChange"
          bordered
        >
          <template #bodyCell="{ index, column, record }">
            <template v-if="column.key === 'index'">
              <div>{{ index + 1 }}</div>
            </template>
            <template v-if="column.key === 'size'">
              <div>{{ (+record.size / 1024).toFixed(2) + ' KB' }}</div>
            </template>
            <template v-if="column.key === 'operation'">
              <a-space>
                <a-button size="small" @click.stop="openFilePreview(record as TableRowFeilds)">查看</a-button>
                <a-popconfirm title="确定删除?" @confirm="onDelete(record as TableRowFeilds)">
                  <a-button danger size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </section>
    <a-modal v-model:open="open" :width="900" title="查看文件" :maskClosable="false" centered destroyOnClose>
      <template #footer>
        <a-button key="back" @click="handleClose">关闭</a-button>
      </template>
      <section class="modal-content-box">
        <a-image
          v-if="isImage"
          width="100%"
          :preview="{
            visible: imgVisible,
            onVisibleChange: setVisible,
          }"
          :src="imageUrl"
        />
      </section>
    </a-modal>
  </section>
</template>

<script setup lang="ts">
import { FileService } from '@/api'
import type { TableColumnsType, TableProps } from 'ant-design-vue'
import { Pagination, SearchForm, TableRowFeilds } from './types'
defineOptions({ name: 'File' })

// 分页器配置
const pageSet = ref<Pagination>({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ['10', '20', '30', '50', '100'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `总数：${total} 条`
  },
})

// 搜素表单
const searchRormRef = ref()
const searchFormState = reactive<SearchForm>({
  name: '',
})
function onFinishSearch(values: SearchForm): void {
  console.log('Search-Params:', values)
  pageSet.value.current = 1
  getListData()
}
// 重置搜索表单
function resetSearchForm(): void {
  searchRormRef.value.resetFields()
  pageSet.value.current = 1
  getListData()
}
const disabledSeachBtn = computed(() => {
  return !searchFormState.name
})

const mainContentRef = ref<HTMLElement>()
const tableHeight = ref<number>(500)
const columns: TableColumnsType = [
  { title: '序号', width: 80, dataIndex: 'index', key: 'index', fixed: 'left', align: 'center' },
  { title: '文件名称', minWidth: 150, dataIndex: 'name', key: 'name', fixed: 'left', align: 'center' },
  { title: '文件源名', dataIndex: 'originalname', key: 'originalname', minWidth: 150, align: 'center' },
  { title: '文件大小', dataIndex: 'size', key: 'size', minWidth: 150, align: 'center' },
  { title: '文件路径', dataIndex: 'url', key: 'url', minWidth: 150, align: 'center' },
  { title: 'MIME', dataIndex: 'mime', key: 'mime', minWidth: 150, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', minWidth: 150, align: 'center' },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    align: 'center',
    width: 120,
  },
]
const tableLoading = ref<boolean>(false)
const tableData = ref<TableRowFeilds[]>([])

function handleTableChange(pag: { pageSize: number; current: number }, filters: any, sorter: any): TableProps['onChange'] {
  console.log('pag:==>', pag)
  console.log('filters:==>', filters)
  console.log('sorter:==>', sorter)
  pageSet.value = Object.assign(pageSet.value, pag)
  getListData()
  return
}

// 确定删除
async function onDelete(record: TableRowFeilds) {
  const row = toRaw(record)
  console.log('onDelete:==>', row)
  const res = await FileService.remove(row?.id)
  if (res?.success) {
    window.$message.success('删除文件成功！')
    getListData()
    return true
  } else {
    window.$message.error('删除文件失败！' + res?.message)
    return false
  }
}
// 设置图片预览是否显示
const imgVisible = ref<boolean>(false)
const imageUrl = ref<string>('')
function setVisible(value: boolean): void {
  console.log('setVisible:==>', value)
  imgVisible.value = value
}

// 文件查看弹窗是否显示
const open = ref<boolean>(false)
// 是否为图片类型
const isImage = ref<boolean>(false)

// 弹窗关闭后的回调
function handleClose() {
  open.value = false
  isImage.value = false
  imageUrl.value = ''
}

// 查看文件
function openFilePreview(record: TableRowFeilds) {
  const row = toRaw(record)
  imageUrl.value = row.url
  isImage.value = row.mime?.includes('image')
  open.value = true
  nextTick(() => {
    // setVisible(true)
    // console.log('openFilePreview:==>', row)
  })
}

// 获取列表数据
async function getListData() {
  tableLoading.value = true
  const params: FileEntity.SearchParams = {
    page: pageSet.value.current,
    pageSize: pageSet.value.pageSize,
    name: searchFormState.name,
  }
  const res = await FileService.page(params)
  console.log('getList：==>', res)
  if (res?.success) {
    const list = res?.data?.list || []
    tableData.value = list
    pageSet.value.total = res?.data?.total || 0
  } else {
    tableData.value = []
  }
  tableLoading.value = false
}

onMounted(() => {
  if (mainContentRef.value) {
    tableHeight.value = mainContentRef.value.offsetHeight - 64
    console.log('tableHeight:==>', tableHeight.value)
  }
  getListData()
})
</script>

<style lang="scss" scoped>
.main-box {
  width: 100%;
  height: calc(100% - 76px);
  margin-top: 12px;

  .main-content {
    width: 100%;
    height: calc(100% - 52px);
  }
}
.modal-content-box {
  padding-top: 24px;
  height: 700px;
  width: 100%;
  overflow: hidden auto;
}
</style>
